package com.fasteat.netty.server;

import com.fasteat.netty.handler.ChatHandler;
import com.fasteat.netty.handler.HeartBeatHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class ChatServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //获取管道
        ChannelPipeline pipeline =socketChannel.pipeline();
        //websocket基于http协议，使用http的编码和解码器
        pipeline.addLast(new HttpServerCodec());
        //对写大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(1024 * 64));
        //浏览器请求时 ws://ip:port/ws 表示请求的uri,将 http协议升级为 ws协议
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //心跳检测
        pipeline.addLast(new IdleStateHandler(600, 600, 600, TimeUnit.SECONDS));
        pipeline.addLast(new HeartBeatHandler());

        pipeline.addLast(new ChatHandler());
    }
}
